package org.ricks.net;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author chenwei
 * @Description:
 * @date 2022/10/1213:49
 */
public class IoBuffer {

    private ByteOrder order = ByteOrder.LITTLE_ENDIAN;

    private int from = 0;
    private int to = 0;
    private ByteBuffer buffer;

    public IoBuffer(int size) {
        buffer = ByteBuffer.allocate(size).order(order);
    }

    public IoBuffer(int size, ByteOrder order) {
        this.order = order;
    }

    public void skipBytes(int len) {
        if(from +len <=to){
            buffer.position(buffer.position() + len);
            from += len;
        }
    }

    public int readableBytes() {
        return to -from;
    }

    public int writableBytes() {
        return buffer.capacity() - to;
    }

    public IoBuffer put( byte v) {
        buffer.put(v);
        to += 1;
        return this;
    }

    public IoBuffer put(byte[] v) {
        buffer.put(v);
        to += v.length;
        return this;
    }

    public IoBuffer put(ByteBuffer data, int size) {
        byte[] bytes = new byte[size];
        data.get(bytes);
        buffer.put(bytes);
        to += size;
        return this;
    }

    public IoBuffer put(byte[] data,int start,int size) {
        buffer.put(data,start,size);
        to += size;
        return this;
    }

    public IoBuffer putShort(short v) {
        buffer.putShort(v);
        to += 2;
        return this;
    }

    public IoBuffer putInt(int v) {
        buffer.putInt(v);
        to += 4;
        return this;
    }

    public byte get() {
        from += 1;
        return buffer.get(from-1);
    }

    public short getShort() {
        from += 2;
        return buffer.getShort(from-2);
    }

    public int getInt() {
        from += 4;
        return buffer.getInt(from-4);
    }

    public byte[] array() {
        buffer.position(from);

        byte[] bytes= new byte[to-from];
        buffer.get(bytes);
        return bytes;
    }

    public ByteBuffer toByteBuffer() {
        return ByteBuffer.wrap(array());
    }

    public void clear() {
        buffer.clear();
        from=0;
        to=0;
    }
}
